package com.qen.common;

import com.qen.segments.SelectCache;
import org.beetl.sql.clazz.ClassDesc;
import org.beetl.sql.clazz.ColDesc;
import org.beetl.sql.clazz.NameConversion;
import org.beetl.sql.clazz.TableDesc;
import org.beetl.sql.clazz.kit.JavaType;
import org.beetl.sql.core.SQLManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * select缓存
 *
 * @author licz
 * @since 1.0.0
 */
public class ColumnCache {

    private static final Map<Class<?>, List<SelectCache>> LIST_CACHE = new ConcurrentHashMap<>();

    private static final Map<Class<?>, FieldStringMap<SelectCache>> MAP_CACHE = new ConcurrentHashMap<>();

    public static List<SelectCache> getListField(Class<?> clazz) {
        return LIST_CACHE.computeIfAbsent(clazz, c -> {
            SQLManager sqlManager = BeetlUtils.getSQLManager();
            ClassDesc desc = sqlManager.getClassDesc(clazz);
            TableDesc tableDesc = TableInfoHelper.getTableInfo(clazz);
            List<SelectCache> list = new ArrayList<>();
            NameConversion nc = sqlManager.getNc();
            String idAttr = desc.getIdAttr();
            String idCol = nc.getColName(idAttr);
            ColDesc idColDesc = tableDesc.getColDesc(idCol);
            for (String attr : desc.getAttrs()) {
                if (attr.equals(idAttr)) {
                    list.add(new SelectCache(
                            clazz, true, idCol, JavaType.jdbcJavaTypes.get(idColDesc.getSqlType()),
                            idAttr, true, idColDesc
                    ));
                } else {
                    String col = nc.getColName(attr);
                    ColDesc colDesc = tableDesc.getColDesc(col);
                    list.add(
                            new SelectCache(clazz, false, col, JavaType.jdbcJavaTypes.get(colDesc.getSqlType()),
                                    attr, true, colDesc)
                    );
                }
            }
            return list;
        });
    }

    public static Map<String, SelectCache> getMapField(Class<?> clazz) {
//        return MAP_CACHE.computeIfAbsent(clazz,
//                c -> getListField(c).stream().collect(
//                        Collectors.toMap(i -> i.getColumProperty().toUpperCase(Locale.ENGLISH),
//                Function.identity(), (i, j) -> j, FieldStringMap::new)));
        return MAP_CACHE.computeIfAbsent(clazz,
                c -> getListField(c).stream().collect(
                        Collectors.toMap(i -> i.getColumProperty(),
                                Function.identity(), (i, j) -> j, FieldStringMap::new)));
    }
}
